package com.lzjy.tw.composedemo.ui.screen.home.note

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lzjy.tw.composedemo.domain.model.TestModel
import com.lzjy.tw.composedemo.repository.impl.INoteRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import okhttp3.Dispatcher
import javax.inject.Inject

@HiltViewModel
class NoteViewModel @Inject constructor(
    private val noteRepository: INoteRepository
) : ViewModel() {

    private var _testValue = MutableStateFlow<List<TestModel>>(listOf())
    val testValue = _testValue.asStateFlow()

    init {

        insertData()

        queryAll()
    }

    private fun insertData() {
        viewModelScope.launch(Dispatchers.IO)  {
            var testModel: TestModel
            for (i in 0..10) {
                testModel = TestModel(0, i, 2f * i, 3 * i, listOf())
                noteRepository.insert(testModel)
            }
        }
    }

    private fun queryAll() {
        viewModelScope.launch(Dispatchers.IO) {
            noteRepository.getAllNote().collect {
                _testValue.value = it
            }
        }
    }

    fun query(owner_id: Int) {
        viewModelScope.launch {
            noteRepository.getNote(owner_id).collect {
                _testValue.value = it
            }
        }
    }
}